/*
 * Main page for portal
 */

package se.bth.ke.firstfriend.web;

import com.sun.jersey.api.core.InjectParam;
import de.nixis.commons.web.base.Controller;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.springframework.stereotype.Component;
import se.bth.ke.firstfriend.model.Article;
import se.bth.ke.firstfriend.model.Topic;
import se.bth.ke.firstfriend.dto.PortalMainPageDTO;
import se.bth.ke.firstfriend.model.dto.TopicInfo;

/**
 *
 * @author markus, nico.rehwaldt
 */
@Component
@Path("/")
public class PortalController extends Controller {

    @InjectParam
    private TopicController topicController;

    @InjectParam
    private UserController userController;
    
    @PersistenceContext
    private EntityManager em;
    
    @GET
    public PortalMainPageDTO index() {
        List<TopicInfo> infos = topicController.getTopicInfos();

        for (TopicInfo topic: infos) {
            topic.setArticles(getArticlesOf(topic));
        }
        return new PortalMainPageDTO(infos);
    }

    @GET
    @Path("/portal")
    public Topic portal() {
        return new Topic("bar");
    }

    private List<Article> getArticlesOf(TopicInfo topic) {
        return em.createQuery("SELECT a FROM Topic t JOIN t.articles a WHERE t = :topic")
                 .setMaxResults(4)
                 .setParameter("topic", topic.getTopic())
                 .getResultList();
    }
}
